package edu.yuhf.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.yuhf.dao.iface.HobbyDao;
import edu.yuhf.dao.iface.UserDao;
import edu.yuhf.domain.Hobby;
import edu.yuhf.domain.Page;
import edu.yuhf.domain.User;
import edu.yuhf.domain.UserDetail;
import edu.yuhf.service.iface.UserService;
import edu.yuhf.web.dto.UserForm;

@Transactional
@Service
public class UserServiceImpl implements UserService {

	@Resource
	UserDao userDao;
	
	@Resource
	HobbyDao hobbyDao;
	
	@Override
	public boolean checkUser(String name, String password) {
		boolean flag=false;
		User user=new User(0l,name,password,"","");
		if(userDao.queryUserByNameAndPwd(user)==1) {
			flag=true;
		}
		return flag;
	}

	@Override
	public boolean addUser(User user, UserDetail ud) {
		boolean flag=false;
		int userId=userDao.insertUser(user);
		int rowNumber=userDao.insertUserDetail(userId,ud);
		if(userId!=0&&rowNumber==1) {
			flag=true;
		}
		return flag;
	}
	
	private void replaceHobbyName(List<UserForm> list) {
		List<Hobby> hobbys=hobbyDao.getHobbyAll();
		for(Hobby hobby:hobbys) {
			for(UserForm uf:list) {
				String hobbyString=uf.getHobby();
				if(hobbyString!=null&&hobbyString.indexOf(String.valueOf(hobby.getCode()))!=-1) {
					String newHobbyString=hobbyString.replace(String.valueOf(hobby.getCode()), hobby.getName());
					uf.setHobby(newHobbyString);
				}
			}
		}		
	}

	@Override
	public List<UserForm> showUser() {
		List<UserForm> list=userDao.queryUserAll();
		this.replaceHobbyName(list);
		return list;
	}

	@Override
	public void showUserForPage(Page<UserForm> page,String keyword) {
		userDao.queryUserForPage(page, keyword);
		this.replaceHobbyName(page.getPageList());
	}

}
